package com.wfl.sampling.service.impl;

import com.wfl.sampling.service.FileStorageService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import org.springframework.util.StringUtils;
public class FileStorageServiceImpl implements FileStorageService{
    @Value("${file.upload-dir}")
    private String uploadDir;
    @Override
    public String storeFile(MultipartFile file) {
        // 用于规范化文件名
        String fileName = StringUtils.cleanPath(file.getOriginalFilename());

        // 检查文件名是否包含无效字符
        if(fileName.contains("..")) {
            throw new RuntimeException("Invalid file path: " + fileName);
        }

        try {
            // 将文件存储在目标位置（替换同名文件）
            Path fileStorageLocation = Paths.get(uploadDir).toAbsolutePath().normalize();
            Files.createDirectories(fileStorageLocation); // 如果不存在就创建目录

            // 将文件复制到目标位置（替换同名文件）
            Path targetLocation = fileStorageLocation.resolve(fileName);
            Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);

            return fileName;
        } catch (IOException ex) {
            throw new RuntimeException("Could not store file " + fileName + ". Please try again!", ex);
        }
    }

    @Override
    public Resource loadFileAsResource(String fileName) {
        // 这里写逻辑来加载文件
        return null;
    }

}
